#include "logdialog.h"
#include "ui_logdialog.h"

LogDialog::LogDialog(const QString &fileName, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LogDialog)
{
    ui->setupUi(this);

    m_fileName = fileName;
}

LogDialog::~LogDialog()
{
    delete ui;
}

void LogDialog::on_hideButton_clicked()
{
    hide();
}

void LogDialog::msg(const QString msg)
{
    QTime curTime = QTime::currentTime();
    QString logMsg = curTime.toString("[hh:mm:ss:zzz] ") + msg;

    ui->logEdit->append(logMsg);
    if (maxTextLength < ui->logEdit->toPlainText().length()) {
        ui->logEdit->clear();
    }

    QFile file(m_fileName);
    if (file.open(QFile::WriteOnly | QFile::Append | QFile::Text)) {
        QTextStream out(&file);
        out << logMsg << "\n";

        if (4194304 < file.size()) {
            QDateTime cur = QDateTime::currentDateTime();
            QString logFileName = QApplication::applicationDirPath();
            logFileName += cur.toString(QString("/log/yyyyMMdd-hhmmss-c.log"));

            QFile file2(logFileName);
            if (file2.open(QFile::WriteOnly | QFile::Append | QFile::Text)) {
                QTextStream out2(&file2);
                out2 << m_fileName << "\n";
                out2 << "+++ Continue +++" << "\n";
            }

            m_fileName = logFileName;
        }
    }
}

void LogDialog::save(const QString fileName)
{
    QFile file(fileName);
    if (file.open(QFile::WriteOnly | QFile::Text)) {
        QTextStream out(&file);
        out << ui->logEdit->toPlainText();
    }
}
